import React, { useState } from 'react'
import {
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Switch,
  Tag,
  message,
  Popconfirm,
  Divider,
  Row,
  Col,
  Tree,
  Typography,
  TreeSelect,
  Descriptions
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ApartmentOutlined,
  UserOutlined,
  PhoneOutlined,
  MailOutlined,
  EnvironmentOutlined
} from '@ant-design/icons'

const { Title } = Typography
const { TextArea } = Input

// 模拟部门数据
const initialDepartments = [
  {
    id: 1,
    name: '总公司',
    code: 'ROOT',
    parentId: 0,
    sort: 1,
    status: true,
    manager: '张总',
    phone: '010-12345678',
    email: 'ceo@company.com',
    address: '北京市朝阳区xxx大厦',
    description: '公司总部',
    createTime: '2023-01-01 10:00:00',
    children: [
      {
        id: 2,
        name: '技术研发中心',
        code: 'TECH',
        parentId: 1,
        sort: 1,
        status: true,
        manager: '李技术',
        phone: '010-12345679',
        email: 'tech@company.com',
        address: '北京市海淀区科技园',
        description: '负责技术研发工作',
        createTime: '2023-02-01 14:30:00',
        children: [
          {
            id: 3,
            name: '前端开发部',
            code: 'FE',
            parentId: 2,
            sort: 1,
            status: true,
            manager: '王前端',
            phone: '010-12345680',
            email: 'fe@company.com',
            description: '负责前端开发',
            createTime: '2023-03-01 09:15:00'
          },
          {
            id: 4,
            name: '后端开发部',
            code: 'BE',
            parentId: 2,
            sort: 2,
            status: true,
            manager: '赵后端',
            phone: '010-12345681',
            email: 'be@company.com',
            description: '负责后端开发',
            createTime: '2023-03-02 10:20:00'
          },
          {
            id: 5,
            name: '测试部',
            code: 'QA',
            parentId: 2,
            sort: 3,
            status: true,
            manager: '钱测试',
            phone: '010-12345682',
            email: 'qa@company.com',
            description: '负责质量保障',
            createTime: '2023-03-03 11:30:00'
          }
        ]
      },
      {
        id: 6,
        name: '市场运营中心',
        code: 'MARKET',
        parentId: 1,
        sort: 2,
        status: true,
        manager: '孙市场',
        phone: '010-12345683',
        email: 'market@company.com',
        address: '北京市朝阳区商业区',
        description: '负责市场运营',
        createTime: '2023-02-02 15:45:00',
        children: [
          {
            id: 7,
            name: '市场部',
            code: 'MARKETING',
            parentId: 6,
            sort: 1,
            status: true,
            manager: '周市场',
            phone: '010-12345684',
            email: 'marketing@company.com',
            description: '负责市场推广',
            createTime: '2023-03-10 13:25:00'
          },
          {
            id: 8,
            name: '运营部',
            code: 'OPERATION',
            parentId: 6,
            sort: 2,
            status: true,
            manager: '吴运营',
            phone: '010-12345685',
            email: 'operation@company.com',
            description: '负责用户运营',
            createTime: '2023-03-11 14:35:00'
          }
        ]
      },
      {
        id: 9,
        name: '行政管理中心',
        code: 'ADMIN',
        parentId: 1,
        sort: 3,
        status: true,
        manager: '郑行政',
        phone: '010-12345686',
        email: 'admin@company.com',
        address: '北京市海淀区总部',
        description: '负责行政人事',
        createTime: '2023-02-03 16:20:00',
        children: [
          {
            id: 10,
            name: '人力资源部',
            code: 'HR',
            parentId: 9,
            sort: 1,
            status: true,
            manager: '王人事',
            phone: '010-12345687',
            email: 'hr@company.com',
            description: '负责招聘培训',
            createTime: '2023-03-15 10:40:00'
          },
          {
            id: 11,
            name: '财务部',
            code: 'FINANCE',
            parentId: 9,
            sort: 2,
            status: true,
            manager: '冯财务',
            phone: '010-12345688',
            email: 'finance@company.com',
            description: '负责财务管理',
            createTime: '2023-03-16 11:50:00'
          }
        ]
      }
    ]
  }
]

const Index: React.FC = () => {
  const [departments, setDepartments] = useState(initialDepartments)
  const [modalVisible, setModalVisible] = useState(false)
  const [editingDept, setEditingDept] = useState(null)
  const [selectedDept, setSelectedDept] = useState(null)
  const [expandedKeys, setExpandedKeys] = useState(['1', '2', '6', '9'])
  const [form] = Form.useForm()

  // 将部门数据转换为树形结构
  const convertToTreeData = data => {
    return data.map(item => ({
      key: item.id,
      title: (
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between'
          }}
        >
          <span>{item.name}</span>
          <Tag color={item.status ? 'green' : 'red'} size='small'>
            {item.status ? '启用' : '停用'}
          </Tag>
        </div>
      ),
      icon: <ApartmentOutlined />,
      children: item.children ? convertToTreeData(item.children) : [],
      isLeaf: !item.children || item.children.length === 0,
      data: item
    }))
  }

  const treeData = convertToTreeData(departments)

  // 获取所有部门选项（用于父部门选择）
  const getAllDepartments = (depts, level = 0) => {
    let allDepts = []
    depts.forEach(dept => {
      allDepts.push({
        value: dept.id,
        label: `${'─'.repeat(level)} ${dept.name}`,
        disabled: editingDept && dept.id === editingDept.id
      })
      if (dept.children) {
        allDepts = [...allDepts, ...getAllDepartments(dept.children, level + 1)]
      }
    })
    return allDepts
  }

  const departmentOptions = getAllDepartments(departments)

  // 显示详情模态框
  const showDetailModal = dept => {
    setSelectedDept(dept)
    setDetailModalVisible(true)
  }

  // 显示编辑/新增模态框
  const showModal = (dept = null) => {
    setEditingDept(dept)
    if (dept) {
      form.setFieldsValue({
        ...dept,
        parentId: dept.parentId || 0
      })
    } else {
      form.resetFields()
      form.setFieldsValue({
        parentId: selectedDept ? selectedDept.id : 0,
        sort: 1,
        status: true
      })
    }
    setModalVisible(true)
  }

  // 处理表单提交
  const handleSubmit = values => {
    if (editingDept) {
      // 编辑部门
      const updateDepartment = depts => {
        return depts.map(dept => {
          if (dept.id === editingDept.id) {
            return { ...dept, ...values }
          }
          if (dept.children) {
            return { ...dept, children: updateDepartment(dept.children) }
          }
          return dept
        })
      }
      setDepartments(updateDepartment(departments))
      message.success('部门更新成功')
    } else {
      // 新增部门
      const newDept = {
        id: Math.max(...getAllDeptIds(departments)) + 1,
        ...values,
        createTime: new Date().toLocaleString()
      }

      const addDepartment = (depts, parentId, newDept) => {
        return depts.map(dept => {
          if (dept.id === parentId) {
            return {
              ...dept,
              children: [...(dept.children || []), newDept]
            }
          }
          if (dept.children) {
            return {
              ...dept,
              children: addDepartment(dept.children, parentId, newDept)
            }
          }
          return dept
        })
      }

      setDepartments(addDepartment(departments, values.parentId, newDept))
      message.success('部门创建成功')
    }
    setModalVisible(false)
  }

  // 获取所有部门ID
  const getAllDeptIds = depts => {
    let ids = []
    depts.forEach(dept => {
      ids.push(dept.id)
      if (dept.children) {
        ids = [...ids, ...getAllDeptIds(dept.children)]
      }
    })
    return ids
  }

  // 删除部门
  const handleDelete = deptId => {
    const deleteDepartment = depts => {
      return depts.filter(dept => {
        if (dept.id === deptId) {
          return false
        }
        if (dept.children) {
          dept.children = deleteDepartment(dept.children)
        }
        return true
      })
    }
    setDepartments(deleteDepartment(departments))
    message.success('部门删除成功')
  }

  // 树节点选择
  const onSelect = (selectedKeys, { node }) => {
    setSelectedDept(node.data)
  }

  // 树节点展开
  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys)
  }

  return (
    <div className='department-management'>
      <Row gutter={16}>
        {/* 左侧部门树 */}
        <Col span={8}>
          <Card>
            <div
              style={{
                marginBottom: 16,
                display: 'flex',
                justifyContent: 'space-between'
              }}
            >
              <Title level={4} style={{ margin: 0 }}>
                <ApartmentOutlined style={{ marginRight: 12 }} />
                部门组织
              </Title>
              <Button
                type='primary'
                icon={<PlusOutlined />}
                onClick={() => showModal()}
              >
                新增部门
              </Button>
            </div>

            <Tree
              treeData={treeData}
              expandedKeys={expandedKeys}
              selectedKeys={selectedDept ? [selectedDept.id] : []}
              onSelect={onSelect}
              onExpand={onExpand}
              showIcon
              defaultExpandAll
              style={{ padding: '8px 0' }}
            />
          </Card>
        </Col>

        {/* 右侧详情和操作 */}
        <Col span={16}>
          <Card>
            {selectedDept ? (
              <>
                <div
                  style={{
                    marginBottom: 16,
                    display: 'flex',
                    justifyContent: 'space-between'
                  }}
                >
                  <Title level={4} style={{ margin: 0 }}>
                    {selectedDept.name}
                    <Tag
                      color={selectedDept.status ? 'green' : 'red'}
                      style={{ marginLeft: 12 }}
                    >
                      {selectedDept.status ? '启用' : '停用'}
                    </Tag>
                  </Title>
                  <Space>
                    <Button
                      icon={<EditOutlined />}
                      onClick={() => showModal(selectedDept)}
                    >
                      编辑
                    </Button>
                    <Popconfirm
                      title='确定要删除这个部门吗？'
                      onConfirm={() => handleDelete(selectedDept.id)}
                      okText='确定'
                      cancelText='取消'
                    >
                      <Button icon={<DeleteOutlined />} danger>
                        删除
                      </Button>
                    </Popconfirm>
                  </Space>
                </div>

                <Descriptions bordered column={2}>
                  <Descriptions.Item label='部门编码'>
                    {selectedDept.code}
                  </Descriptions.Item>
                  <Descriptions.Item label='排序'>
                    {selectedDept.sort}
                  </Descriptions.Item>
                  <Descriptions.Item label='负责人' span={2}>
                    <UserOutlined style={{ marginRight: 8 }} />
                    {selectedDept.manager}
                  </Descriptions.Item>
                  <Descriptions.Item label='联系电话'>
                    <PhoneOutlined style={{ marginRight: 8 }} />
                    {selectedDept.phone}
                  </Descriptions.Item>
                  <Descriptions.Item label='邮箱'>
                    <MailOutlined style={{ marginRight: 8 }} />
                    {selectedDept.email}
                  </Descriptions.Item>
                  {selectedDept.address && (
                    <Descriptions.Item label='地址' span={2}>
                      <EnvironmentOutlined style={{ marginRight: 8 }} />
                      {selectedDept.address}
                    </Descriptions.Item>
                  )}
                  <Descriptions.Item label='描述' span={2}>
                    {selectedDept.description}
                  </Descriptions.Item>
                  <Descriptions.Item label='创建时间'>
                    {selectedDept.createTime}
                  </Descriptions.Item>
                </Descriptions>

                <Divider />

                <div style={{ textAlign: 'center' }}>
                  <Button
                    type='primary'
                    onClick={() => showModal()}
                    icon={<PlusOutlined />}
                  >
                    在此部门下新增子部门
                  </Button>
                </div>
              </>
            ) : (
              <div
                style={{
                  textAlign: 'center',
                  padding: '40px 0',
                  color: '#999'
                }}
              >
                <ApartmentOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                <div>请选择左侧的部门查看详情</div>
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* 新增/编辑部门模态框 */}
      <Modal
        title={editingDept ? '编辑部门' : '新增部门'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form form={form} layout='vertical' onFinish={handleSubmit}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name='name'
                label='部门名称'
                rules={[{ required: true, message: '请输入部门名称' }]}
              >
                <Input placeholder='请输入部门名称' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name='code'
                label='部门编码'
                rules={[{ required: true, message: '请输入部门编码' }]}
              >
                <Input placeholder='请输入部门编码' />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name='parentId' label='父部门'>
            <TreeSelect
              treeData={[
                { value: 0, label: '根部门', children: departmentOptions }
              ]}
              placeholder='请选择父部门'
              treeDefaultExpandAll
            />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name='sort'
                label='排序'
                rules={[{ required: true, message: '请输入排序号' }]}
              >
                <InputNumber min={1} max={999} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name='status' label='状态' valuePropName='checked'>
                <Switch checkedChildren='启用' unCheckedChildren='停用' />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name='manager' label='负责人'>
                <Input placeholder='请输入负责人姓名' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name='phone' label='联系电话'>
                <Input placeholder='请输入联系电话' />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name='email' label='邮箱'>
            <Input placeholder='请输入邮箱地址' />
          </Form.Item>

          <Form.Item name='address' label='地址'>
            <Input placeholder='请输入部门地址' />
          </Form.Item>

          <Form.Item name='description' label='部门描述'>
            <TextArea rows={3} placeholder='请输入部门描述' />
          </Form.Item>

          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type='primary' htmlType='submit'>
                {editingDept ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Index
